package createtask;

import java.io.IOException;
import java.sql.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import channel.Channel;

import page.PageState;
import task.Task;
import thelist.thelistChannel;
import usr.Usr;

public class CreateTask extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			HttpSession sess = req.getSession();
			Usr usr = (Usr)sess.getAttribute("usr");
			if(usr == null)
			{
				req.setAttribute("error_cause", PageState.LOGIN_NOT_EXIST);
				req.getRequestDispatcher("login.jsp").forward(req, resp);
				return;
			}
			
			int pay = usr.getPay();
			if(usr.createTask() == true)
			{
				int ithisType = (Integer)sess.getAttribute("thisType");
				int ithatType = (Integer)sess.getAttribute("thatType");
				String sthisType = thelistChannel.listChannelbyName(ithisType);
				String sthatType = thelistChannel.listChannelbyName(ithatType);
				String createLog = String.format("if %s then %s, use money %d\n", 
						sthisType, sthatType, pay);
				usr.appLog(createLog);
				usr.writeLog();
				usr.modify();
			}
			else
			{
				req.setAttribute("error_money", "fuck");
				req.getRequestDispatcher("newtask.jsp").forward(req, resp);
				return;
			}
			
			String desc = req.getParameter("desc");
			Channel thisChannel = (Channel) sess.getAttribute("this");
			Channel thatChannel = (Channel) sess.getAttribute("that");
			Task task = new Task(thisChannel, thatChannel);
			task.setDesc(desc);
			task.setUsr(usr.getId());
			task.create();
			
			sess.removeAttribute("this");
			sess.removeAttribute("thisType");
			sess.removeAttribute("that");
			sess.removeAttribute("thatType");
			
			resp.sendRedirect("tasks.jsp");
		}
		catch (IOException | ServletException  e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

}
